<?php
class Integral_logModel extends Model {
    public function _list($view,$join, $field,$map,$rename = 'r',$pagesize=20) {
		//计算总页数
		$count = $this->alias($rename)->join($join)->where($map)->count();
		import('ORG.Util.Page');
		//实例化分页类
		$p = new Page($count, $pagesize);
		$order=' r.id desc';
		if(!empty($_REQUEST['order'])){
			$order=$_REQUEST['order'].' '.$_REQUEST['order_type'].','.$order;	
		}
		$list = $this->alias($rename)->join($join)->where($map)->Field($field)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();
		$pages = $p->show();
		//$_REQUEST['list']=$list;
		$view->assign('list',$list);
		$view->assign('pages',$pages);
		return $pages;
    }
	//public function giveIntegral(){}
	public function filter($type='integral_log'){
		if($type=='apply'){
			//筛选该录指定的上司是当前用户
			$where['r.member_id']=session(C('USER_AUTH_KEY'));
			$where['r.pid']=array('like','%'.session(C('USER_AUTH_KEY')).'%');
			$where['_logic']='or';
			$map['_complex']=$where;
			//筛选状态
			if(""!=trim($_REQUEST['statu_id'])){
				$map['r.statu_id']=$_REQUEST['statu_id'];    
			}else{
				$map['r.statu_id']=array('neq',0);    
			}
		}
        //筛选积分类型
        if(trim($_REQUEST['type_id'])!=''){
            $map['r.type_id']=$_REQUEST['type_id'];
        }
        //筛选积分规则 或 积分规则的类型
        if(trim($_REQUEST['rule_id'])!=''){
            $map['r.rule_id']=$_REQUEST['rule_id'];
        }else{
            if(trim($_REQUEST['ruletypeid'])!=''){
               $ruletypeid=D("Integral_rule")->where(array("type_id"=>$_REQUEST['ruletypeid']))->getField('id',true);
            }    
        }
//		if(trim($_REQUEST['keywords'])){
//			$map['m.company_id']=$_REQUEST['keywords'];
//		}
		
		if(isset($_REQUEST['pos_id'])){
			$map['r.memberpositionid']=array('LIKE', '%,'.$_REQUEST['pos_id'].',%');
		}
		
		
		if(!empty($_REQUEST['formtype_id'])){
			$formtype=D('Form')->where(['formcategory_id'=>$_REQUEST['formtype_id']])->getField('id',true);
			if(!empty($formtype)){$map['r.form_id']=['in',implode(',',$formtype)];}
			else{$map['r.form_id']=1;}
		}
        //筛选开始时间与结束时间
        if(trim($_REQUEST['starttime'])!=''){
            $map['r.time']=array('GT',strtotime($_REQUEST['starttime']));
        }
        if(trim($_REQUEST['endtime'])!=''){
            $map['r.time']=array('LT',strtotime($_REQUEST['endtime']));
        }
        if(""==trim($_REQUEST['starttime'])&&""==trim($_REQUEST['endtime'])){
            //$map['r.time']=array('between',$this->getCurMonthDay());
        }
		//默认获取这个月的记录
        if(""!=trim($_REQUEST['starttime'])&&""!=trim($_REQUEST['endtime'])){
            $map['r.time']=array('between',array(strtotime($_REQUEST['starttime']),strtotime($_REQUEST['endtime'])));
        }
        //筛选积分是加分还是减分（大于0或小于0）
        if($_REQUEST['rewardstype']==1){
            $map['r.changenum']=array('GT',0);
        }
        if($_REQUEST['rewardstype']==2){
            $map['r.changenum']=array('LT',0);
        }
        //筛选某个职员 或一整个部门
        if(""!=trim($_REQUEST['member_id'])){
            $map['r.member_id']=$_REQUEST['member_id'];    
        }else{
			if(""!=trim($_REQUEST['groupid'])){
				//$map['g.id']=$_REQUEST['groupid'];
			}
        }
        $map['r.site_id']=__SITEID__;
		
		if($type=='integral_log'){
        	$map['r.statu_id']=array('in','0,1');
		}
		return $map;
	}
	//获取这个月第一天到第最后一天的时间戳
	private function getCurMonthDay(){
		return [strtotime(date('Y-m-01 00:00:00',time())),strtotime(date('Y-m-d 23:59:59',strtotime(date('Y-m-01 00:00:00',time()))).' +1 month -1 day')];	
	}
	//获取总数
	public function getTotalnum($join,$map,$rename='r',$field='changenum'){
		return $this->alias($rename)->join($join)->where($map)->sum($field);
	}
	//更新数据
	public function update($data){
		if(isset($data['id'])){
			$result=$this->changeTotalnum($data['id'],$data['member_id'],$data['changenum'],0);//0更新，1删除
			if (false !== $result) {
				$numbefore=$this->where('id ='.$data['id'])->getfield('changenum');
				$numdiff=$data['changenum']-$numbefore;
				$totalbefore=$this->where('id ='.$data['id'])->getfield('totalnum');
				$data['totalnum']=$totalbefore+$numdiff;
				$res = $this->where('id ='.$data['id'])->save($data);
				if(false !== $res){
					$dat['total']=$data['totalnum'];
					$data['logid']=$data['id'];
					unset($data['id']);
					$r=D('Integralranking')->where('integrallogid ='.$data['logid'])->setField('total',$dat['total']);
					if(false !== $r){
						$re=D('Integralranking')->updateData($data);
						if(false !== $re){
							return true;
						}
					}
				}
			}
			return false;
		}
	}
	//更改总积分（integral_log 表和 integralranking 表）
	public function changeTotalnum($id,$mid,$num,$action){//$action 0更新,1删除
		
		$id_arr=$this->where('member_id ='.$mid.' and id > '.$id)->getfield('id',true);
		foreach($id_arr as $key => $value){
			if($action == 0){//更新
				$numbefore=$this->where('id ='.$id)->getfield('changenum');
				$numdiff=$num-$numbefore;
			}elseif($action == 1){//删除
				$numdiff=$num;
			}
			$totalbefore=$this->where('id ='.$value)->getfield('totalnum');
			$data['totalnum']=$totalbefore+$numdiff;
			$re=$this->where('id ='.$value)->save($data);
			if (false === $re) {
				return false;
			}else{
				$dat['total']=$totalbefore+$numdiff;
				$res=D('Integralranking')->where('integrallogid ='.$value)->save($dat);
				if(false === $res){
					return false;
				}
			}
		}
		return true;
	}
	
	public function inset_log($data,$type=1){
		
		
		$data['remark']=date('Y-m-d',time()).'赠送积分';
		if($type==2){
		$data['remark']=date('Y-m-d',time()).'服务商商品返还';	
			}
		$data['time']=time();
		
		$data['total']=($data['m_total']);
		//if($data['member_id']==11)exit(dump($data));
		
	
		return M('Integral_log')->where('id = '.$data['member_id'])->data($data)->add();
	}
	
	
}
?>